import { Action, Db } from 'uokay'
import database from '../database'
import axios from 'axios'
export default class UserAction extends Action {
    __initial__ () {
        this.user = {
            username:'',
            nickname:'',
            user_id: '',
            gender: '',
            tel: '',
            email: '',
            qq: '',
            avatar: ''
        }
    }
    _build_user_ ( profile ) {
        this.user.username = profile.username
        this.user.nickname = profile.nickname
        this.user.user_id = profile.user_id
        this.user.gender = profile.gender
        this.user.tel = profile.tel
        this.user.email = profile.email
        this.user.qq = profile.qq
        this.user.avatar = profile.avatar
    }
    profile (okay, event, pipe) {
        let data = pipe.get('user')
        sessionStorage.setItem('id', data.id)
        sessionStorage.setItem('username', data.username)
        this._build_user_(data.profile)
        let db = Db.i(database)
        if(data.groups) {
            for(let group of data.groups) {
                db.table('et_group').insert(group)
            }
        }
        if (data.friends) {
            for(let friend of data.friends) {
                db.table('friend').insert(friend)
            }
        }
        okay.go('/', false, 'app')
    }
    modify (okay, event, pipe) {
        let user_id = sessionStorage.getItem('id')
        let key = okay.data.$route.key
        let value = okay.data.$route.value
        return new Promise((resolve, reject) => {
            axios.post('/users/modify',{
                id: user_id,
                key: key,
                value: value
            }).then(result => {
                if(result.data.code == 2000) {
                    resolve('success')
                }else {
                    reject('fail')
                }
            }).catch(err => {
                reject('fail')
            })
        })
    }
    modify_success(okay, event, pipe) {
        this.user[okay.data.$route.key] = okay.data.$route.value
        okay.go('-1', false, 'app')
    }
    modify_fail (okay, event, pipe) {
        alert('修改失败，请重试')
    }
}